﻿using MediatR;
using YiShop.Framework.Data;

namespace YiShop.Framework.EventBus
{
    // 基础设施层（Infrastructure Layer）
    public class MediatrDomainEventDispatcher : IDomainEventDispatcher
    {
        private readonly IMediator _mediator;

        public MediatrDomainEventDispatcher(IMediator mediator)
        {
            _mediator = mediator;
        }

        public async Task DispatchEventsAsync(AggregateRoot aggregate)
        {
            foreach (var domainEvent in aggregate.DomainEvents)
            {
                await _mediator.Publish(domainEvent); // 发布到 MediatR 管道
            }
            aggregate.ClearDomainEvents(); // 清除已处理事件
        }

        public async Task DispatchEventAsync<TEvent>(TEvent domainEvent) where TEvent : IDomainEvent
        {
            await _mediator.Publish(domainEvent);
        }
    }
}